﻿// -----------------------------------------------------------------------
// <copyright file="SublayoutQueryableDatasource.cs" company="">
// TODO: Update copyright text.
// </copyright>
// -----------------------------------------------------------------------

namespace SublayoutQueryableDatasource
{
    using Sitecore.Diagnostics;
    using Sitecore.Pipelines.GetRenderingDatasource;

    /// <summary>
    /// Pipeline that adds support for queries in Datasource Location field of a Layout (prefix them with 'query:')
    /// </summary>
    public class SublayoutQueryableDatasource
    {
        public void Process(GetRenderingDatasourceArgs args) 
        {
            string text = args.RenderingItem["Datasource Location"]; //Get the value from the field
            if (!string.IsNullOrEmpty(text))
            {
                if (text.StartsWith("query:") && !string.IsNullOrEmpty(args.ContextItemPath))
                {
                    var contextItem = args.ContentDatabase.GetItem(args.ContextItemPath);

                    if (contextItem != null)
                    {
                        text = text.Remove(0, 6); //remove the query:
                        var item = contextItem.Axes.SelectSingleItem(text); //Execute the query

                        if (item != null)
                        {
                            args.DatasourceRoots.Add(item);
                        }
                        else
                        {
                            Log.Error(string.Format("SublayoutQueryableDatasource - Error in the sublayout datasource cannot retreive the item. Current Item Path: '{0}'. Query in the sublayout: '{1}'.", contextItem.Paths.FullPath, text), this);
                        }
                    }
                }
            }
        }
    }
}
